<template>
    <el-form :model="form" ref="formRef" label-width="120px" style="padding: 20px;">
        <!-- 表单头部 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="移库单号">
                    <el-input v-model="form.transferNum" placeholder="可不填写，自动生成" disabled></el-input>
                </el-form-item>
            
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="form.rember" :maxlength="300" placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="移库单类型" prop="storage" required>
                    <el-select v-model.number="form.transfer" placeholder="请选择入库类型">
                        <el-option label="移库上架" :value="101"></el-option>
                        <el-option label="仓库移库" :value="102"></el-option>
                        <el-option label="报损移库" :value="103"></el-option>
                    </el-select>
                </el-form-item>
              
                <el-form-item label="制单人">
                    <el-input v-model="form.tranCreator" disabled></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="关联订单号" prop="associatedNum">
                    <el-input v-model="form.associatedNum"></el-input>
                </el-form-item>
            
                <el-form-item label="制单时间">
                    <el-input v-model="form.tranCreationTime" disabled></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <div>
            <el-button type="primary" size="small" icon="el-icon-plus" @click="centerDialogVisible = true"
                style="float: right; margin-bottom: 10px;">新增产品</el-button>
        </div>
        <!-- 产品表格 -->
        <el-table :data="products" style="margin-top: 20px;" border>
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column label="产品名称" prop="productName"></el-table-column>
            <el-table-column label="产品编码" prop="productNum"></el-table-column>
            <el-table-column label="规格" prop="specification"></el-table-column>
            <el-table-column label="批次" prop="batch">
            </el-table-column>
            <el-table-column label="单价" prop="price"></el-table-column>
            <el-table-column label="数量">
                <template #default="{ row }">
                    <el-input v-model.number="row.quantity" size="small" type="number"
                        @input="calculateTotal(row)"></el-input>
                </template>
            </el-table-column>

            <el-table-column label="移入库位" prop="newlocation">
                <template #default="{ row }">
                    <el-select v-model="row.newlocation" placeholder="请选择移入库位" >
                        <el-option label="库位A"value="库位A"></el-option>
                        <el-option label="库位B"value="库位B"></el-option>
                        <el-option label="库位C"value="库位C"></el-option>
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column label="库位" prop="wHouseTypeId" >
                <template #default="{ row }">
                   <p v-if="row.wHouseTypeId==1">默认报损库位</p>
                   <p v-if="row.wHouseTypeId==2">默认报损库位</p>
                   <p v-if="row.wHouseTypeId==3">默认报损库位</p>
                   <p v-if="row.wHouseTypeId==4">默认报损库位</p>
                   <p v-if="row.wHouseTypeId==5">默认报损库位</p>
                   <p v-if="row.wHouseTypeId==6">默认报损库位</p>
                   <p v-if="row.wHouseTypeId==7">默认报损库位</p>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
                <template #default="{ row }">
                    <el-button size="small" icon="el-icon-edit" @click="deleteProduct(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm" style="margin-left: 10px;">取消</el-button>
        </div>
    </el-form>

    <el-dialog v-model="centerDialogVisible" title="选择产品" style="width: 1300px;height: 900px;" center>
        <span>
            <!-- <div class="search-container">
                <el-input v-model="from.ProductId" placeholder="请输入产品编号" clearable :disabled="loading" />
                <el-input v-model="from.ProductName" placeholder="请输入产品名称" clearable :disabled="loading" />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div> -->
            <el-table :data="productsData" style="width: 100%;" border row-key="productId" ref="productTableRef">
                <el-table-column type="selection" />
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="productId" label="产品ID"></el-table-column>
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <el-table-column prop="categoryId" label="类别">
                <template v-slot="scope">
                <p v-if="scope.row.categoryId==1">线材类</p>
                <p v-if="scope.row.categoryId==2">家电类</p>
                </template>
                </el-table-column>
                <el-table-column prop="specification" label="规格"></el-table-column>
                <el-table-column prop="price" label="单价"></el-table-column>
            </el-table>
           <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="page.pageindex"
      v-model:page-size="page.pageSize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageind.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
  </div>
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addSelectedProducts">添加</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElTable } from 'element-plus';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from '@/axios/axiosHelp';

const router = useRouter();
const route = useRoute();
const Store = useCounterStore()

var inboundNum = route.query.inboundNum;
// 表单数据
const form = reactive({
    "pid": 0,
    "transfer":101,
    "transferNum": `CP${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
    "associatedNum": "",
    "batch": '',
    "specifications": '',
    "quantity": "",
    "warehouse": "",
    "originallocation": "",
    "newlocation": "",
    "transfer": 101,
    "tranCreator": Store.user?.userName || '未知用户',
    "tranReviewer": "",
    "tranAuditTime": '',
    "tranAuditstatus": 101,
    "tranCreationTime": new Date().toISOString(),
    "tranModifiedBy": "",
    "proName": "",
    "tranChangeTime":new Date(),
    "rember": "",
    "batch": "",
    "isDelete": 0,
    "shenRember": "",
    "productNum": "",
    "productName": "",
});
// 计算总价
const calculateTotal = (row) => {
    row.price = parseFloat(row.price) || 0;
    row.quantity = parseFloat(row.quantity) || 0;
    row.totalPrice = row.price * row.quantity;
};
// 提交表单
const submitForm = () => {
    // 转换数据类型
    const submitData = reactive({
        //pid:products.value.map(row => `{${row.productId}}`).join(',')
        // outbound:form.outbound,
        transferNum: String(form.transferNum),
        transfer:form.transfer,
        associatedNum: form.associatedNum,
        batch: products.value.map(row => `{${row.batch}}`).join(','),
        tranCreator: Store.user?.userName || '未知用户',
        tranReviewer: "无",
        tranAuditTime: new Date().toISOString(),
        tranAuditstatus: 101,
        tranCreationTime: new Date().toISOString(),
        rember: form.rember,
        productName: products.value.map(row => `{${row.productName}}`).join(','),
        productNum: products.value.map(row => `{${row.productNum}}`).join(','),
        pid: products.value.map(row => `{${row.productId}}`).join(','),
        specifications: products.value.map(row => `{${row.specification}}`).join(','),
        price: products.value.map(row => `{${row.price}}`).join(','),
        quantity: products.value.map(row => `{${row.quantity || ''}}`).join(','),
        totalprice: products.value.map(row => `{${row.totalPrice}}`).join(','),
        newlocation:products.value.map(row => `{${row.newlocation}}`).join(','),
        originallocation: products.value.map(row => `{${row.wHouseTypeId}}`).join(','),
        isDelete: 0,
        shenRember: "无"
    });
    console.log('提交的数据:', submitData); // 打印提交的数据
    // 提交请求
    KongaUrl({
        url:'/activity/api/TranManagement/InsertTranManagement',
        method:'post',
        data:submitData
    })   
    // /activity/api/OutManage/InsertOutManage 
    .then((res => {
        if (res.status==200) {
            ElMessage.success('提交成功');
            router.push('/ShowTranManage');
        }
        else {
            ElMessage.success('提交失败');
        }
    })).catch((error) => {
        if (error.response) {
            ElMessage.error(`提交请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data}`);
        } else if (error.request) {
            ElMessage.error('提交请求已发送，但没有收到响应');
        } else {
            ElMessage.error('提交请求时发生错误: ' + error.message);
        }
        console.error('接口错误：', error);
    });

};

const centerDialogVisible = ref(false)

const page = reactive({
  ProductNum: "",
  ProductName: "",
  Category: "",
  pageindex: 1,
  pageSize: 15,
});
const pageind = reactive({
  totalpage: 0,
  totalcount: 0,
});
const productsData = ref([])
const loading = ref(false)
const productTableRef = ref(null)

const Moks = () => {
    loading.value = true;


    KongaUrl({
    url: "/activity/api/Peoduct/GetProductsByConditions/paginated",
    method: "get",
    params: {
      ProductNum: page.ProductNum,
      ProductName: page.ProductName,
      Category: page.Category,
      pageindex: page.pageindex,
      pageSize: page.pageSize,
    },
  }).then((res) => {
    if (res.status == 200) {
      console.log(res.data);
      productsData.value = res.data.result.list;
      pageind.totalcount = res.data.result.totalcount;
      pageind.totalpage = res.data.result.totalPage;
    }
  });

}

const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
  page.pageSize = val;
  Moks();
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  page.pageindex = val;
  Moks();
};

const handleSearch = () => {
    page.pageindex = 1;
    Moks();
}

const addSelectedProducts = () => {
    if (!productTableRef.value) {
        ElMessage.error("请先搜索产品");
        return;
    }
    const selectedRows = productTableRef.value.getSelectionRows();
    if (selectedRows.length === 0) {
        ElMessage.warning("请至少选择一个产品");
        return;
    }
    const selectedIds = selectedRows.map(row => row.productId);
    console.log('选中的数据',selectedIds)
    folieShow(selectedIds);
    centerDialogVisible.value = false;
};

const products = ref([])
// 在 folieShow 中添加 paramsSerializer 配置
const folieShow = (selectedIds) => {
    KongaUrl.get("/activity/api/Peoduct/GetProductModelsByIds/product-ids", {
        params: {
            productIds: selectedIds // 传递数组 ["1", "2"]
        },
       
        // 自定义参数序列化
        paramsSerializer: (params) => {
            return Object.entries(params).flatMap(([key, value]) => {
                if (Array.isArray(value)) {
                    return value.map(v => `${key}=${encodeURIComponent(v)}`);
                }
                return `${key}=${encodeURIComponent(value)}`;
            }).join('&');
        }
    }).then((res) => {
        console.log('选中的产品数据',res)
        products.value = res.data.map(product => ({
            ...product,
            price: product.price || 0,
            quantity: 0,
            totalPrice: 0,
            batch: `HP${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
            wHouseTypeId: product.wHouseTypeId,
            newlocation:''
        }));
        console.log('选中的产品数据11',products.value)
    }).catch((error) => {
        ElMessage.error("获取产品数据失败：" + error.message);
        console.error("接口错误：", error);
    });
};

// 取消表单操作
const cancelForm = () => {
    // 重置表单数据
    Object.keys(form).forEach(key => form[key] = '');
    // 清空表格数据
    products.value = [];
};

// 自动生成入库单号
onMounted(() => {
    Moks();
    // if (!form.inboundNum) {
    //     generateInboundNumber();
    // }
});

// const generateInboundNumber = async () => {
//     try {
//         const response = await KongaUrl.get('/api/inbound-orders/generate-number');
//         form.inboundNum = response.data;
//     } catch (error) {
//         ElMessage.error('生成移库单号失败');
//     }
// };
const deleteProduct = (row) => {
    products.value = products.value.filter(item => item.productId !== row.productId);
    ElMessage.success('产品删除成功');
}
</script>

<style scoped>
.el-table {
    width: 100%;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.search-container .el-input {
    flex: 1;
    max-width: 200px;
}
</style>